<template>
  <div>
    <div v-if="activeTasks.length > 1" style="margin-bottom: 10px">
      审批节点：
      <el-select @change="getEnableRecallNodes" v-model="actionData.taskId" placeholder="选择要处理的节点">
        <el-option :value="task.taskId" :label="task.name" v-for="task in activeTasks" :key="task.taskId"></el-option>
      </el-select>
      <span style="color: #8c8c8c; margin-left: 10px">要处理哪个任务</span>
    </div>
    <div v-if="action === 'recall'" style="margin-bottom: 10px">
      回退节点：
      <el-select v-model="actionData.targetNode" placeholder="选择要回退到的节点">
        <el-option :value="node.nodeId" :label="node.nodeName" v-for="node in recallNodes" :key="node.nodeId"></el-option>
      </el-select>
      <span v-show="recallNodes.length === 0" style="color: #8c8c8c; margin-left: 10px">暂无可回退节点😅</span>
    </div>
    <div v-if=" action === 'transfer' || action === 'beforeAdd' || action === 'afterAdd'" style="margin-bottom: 10px">
      <span v-if="action === 'transfer'">转交给谁：</span>
      <span v-else>给谁加签：</span>
      <el-button style="margin-right: 20px" size="small" :icon="User" @click="selectUser">选择人员</el-button>
      <el-tag size="small" v-if="actionData.targetUser">{{actionData.targetUser.name }}</el-tag>
    </div>
    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" maxlength="255" show-word-limit
              :placeholder="actionDesc.tip" v-model="actionData.comment.text"></el-input>
    <div class="action-content">
      <div v-if="showSign" style="margin: 10px 0; display: flex; align-items: center">
        <el-button size="small" @click="showSignPanel" :icon="Edit">点击签名</el-button>
        <img :src="actionData.signature" @click="showSignPanel" width="40%" />
        <w-dialog title="请使用鼠标签字" width="700px" v-model="signVisible" @ok="signOk">
          <canvas id="signPanel" width="650px" height="300px"></canvas>
        </w-dialog>
      </div>
      <image-upload class="image-upload" v-model="imageList" placeholder="添加图片" :max-size="10" :max-number="10" :mode="isMobile ? 'MOBILE' : 'PC'"/>
      <file-upload v-model="fileList" placeholder="添加附件" :max-size="100" :max-number="5" :mode="isMobile ? 'MOBILE' : 'PC'"/>
    </div>
    <org-picker :pc-mode="!isMobile" title="选择要转交的人员" type="user" ref="orgPicker" :selected="actionData.targetUser ? [actionData.targetUser] : []" @ok="selected"/>
  </div>
</template>

<script>
import { User, Edit } from '@element-plus/icons-vue'
import SignaturePad from 'signature_pad'
import OrgPicker from '/@/views/setting/workflow/process/OrgPicker.vue'
import ImageUpload from '/@/views/setting/workflow/components/form/ImageUpload.vue'
import FileUpload from '/@/views/setting/workflow/components/form/FileUpload.vue'
import { computed, onMounted, reactive, toRefs, ref } from 'vue'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'
import { isNotEmpty, ok } from '/@/utils/utils'

export default {
    name: 'ProcessAction',
    components: {
        User,
        Edit,
        OrgPicker,
        ImageUpload,
        FileUpload
    },
    props: {
        action: {
            type: String,
            default: 'agree',
        },
        instance: {
            type: Object,
            required: true,
        },
        showSign: {
            type: Boolean,
            default: false,
        },
        activeTasks: {
            type: Array,
            default: () => {
                return []
            },
        },
        actionDesc: {
            type: Object,
            default: () => {
                return {}
            },
        },
        formData: {
            type: Object,
            default: () => {
                return {}
            },
        },
        thickness: {
            type: Number,
            default: 2,
        },
        color: {
            type: String,
            default: '#000',
        },
    },
    emits: ['success'],
    setup(props, context) {
        const { instance, action, thickness,  color, activeTasks} = toRefs(props)
        const orgPicker = ref()
        const state = reactive({
            visible: false,
            hasSign: false,
            signVisible: false,
            signaturePad: null,
            imageList: [],
            fileList: [],
            recallNodes: [],
            actionData: {
                taskId: null,
                signature: '',
                targetNode: null,
                targetUser: null,
                comment: {
                text: '',
                    attachments: [],
                },
            },
        })
        const loginUser = computed(() => {
            return Cookies.get('userId')
        })
        const isMobile = computed(() => {
            return window.screen.width < 450
        })
        const _recallNodes = computed(() => {
            //去重，处理最后一个包含退回节点的后续的节点
            let lastIndex = 0
            instance.value.progress.forEach((p, i) => {
                if (p.result === 'recall') {
                    lastIndex = i
                }
            })
            return instance.value.progress
                .filter((node, i) => {
                    return (
                        node.nodeType === 'APPROVAL' && node.finishTime && i > lastIndex
                    )
                })
                .map((node) => {
                    return { name: node.name, nodeId: node.nodeId }
                })
        })
        const show = () => {
            state.visible = true
        }
        const close = () => {
            state.visible = false
        }
        const showSignPanel = () => {
            state.signVisible = true
            nextTick(() => {
                initSign()
            })
        }
        const loadFormInfo = (id) => {
            // TO DO 接口
            return 
            getModelById(id)
            .then((rsp) => {
                let form = rsp.data
                form.logo = JSON.parse(form.logo)
                state.actionData = form
            })
            .catch((err) => {
                ElMessage.error((err || '获取流程模型失败'))
            })
        }
        const selectUser = () => {
            orgPicker.value.show()
        }
        const selected = (users) => {
            if (users[0].id === loginUser.value){
                ElMessage.warning('不允许加签本人')
            }else {
                state.actionData.targetUser = users[0]
            }
        }
        const initSign = () => {
            state.hasSign = false
            if (state.signaturePad) {
                state.signaturePad.clear()
            } else {
                let canvas = document.getElementById('signPanel')
                state.signaturePad = new SignaturePad(canvas, {
                    penColor: color.value,
                    minWidth: thickness.value,
                    maxWidth: thickness.value + 2,
                })
                state.signaturePad.onEnd = () => {
                    state.hasSign = true
                    //this._value = state.signaturePad.toDataURL()
                }
                if (isMobile.value) {
                    //canvas.height = 300 ;
                    canvas.width = document.body.clientWidth
                }
                //resizeCanvas(canvas)
            }
        }
        const getTask = () => {
            if (isNotEmpty(state.actionData.taskId)) {
                return state.actionData.taskId
            } else if (activeTasks.value.length > 0) {
                return activeTasks.value[0].taskId
            } else if (action.value === 'cancel') {
                const pg = instance.value.progress || []
                for (let i = 0; i < pg.length; i++) {
                    if (pg[i].users) {
                        for (let j = 0; j < pg[i].users.length; j++) {
                            if (!isNotEmpty(pg[i].users[j].finishTime)) {
                                return pg[i].users[j].taskId
                            }
                        }
                    } else {
                        if (!isNotEmpty(pg[i].finishTime)) {
                            return pg[i].taskId
                        }
                    }
                }
            }
            return null
        }
        const getEnableRecallNodes = () => {
            // TO DO 接口
            return 
            getEnableRecallNodes(instance.value.instanceId, getTask())
            .then((rsp) => {
                state.recallNodes = rsp.data
            })
            .catch((err) => {
                ElMessage.error((err || '获取可回退节点失败'))
            })
        }
        const submitAction = () => {
            let params = {
                instanceId: instance.value.instanceId,
                taskId: getTask(),
                comment: {
                    text: state.actionData.comment.text,
                    attachments: state.imageList.concat(state.fileList),
                },
                formData: formData.value,
                signature: null,
                action: action.value,
                targetNode: state.actionData.targetNode,
                targetUser: state.actionData.targetUser
                ? state.actionData.targetUser.id
                : null,
            }
            if (
                (action.value === 'beforeAdd' ||
                action.value === 'afterAdd' ||
                action.value === 'transfer') &&
                !params.targetUser
            ) {
                ElMessage.warning('请设置人员')
                return
            } else if (
                action.value === 'recall' &&
                !isNotEmpty(state.actionData.targetNode)
            ) {
                ElMessage.warning('请选择回退到哪个节点')
                return
            }
            approvalTask(params)
                .then((rsp) => {
                    context.emit('ok')
                    ok(rsp, '处理任务成功')
                    close()
                })
                .catch((err) => {
                    ElMessage.error((err || '处理任务失败'))
                })
        }
        const signOk = () => {
            state.signVisible = false
            state.actionData.signature = state.signaturePad.toDataURL()
        }
        onMounted(() => {
            if (action.value === 'recall') {
                getEnableRecallNodes()
            }
        })
        return {
            ...toRefs(state),
            User,
            Edit,
            loginUser,
            isMobile,
            _recallNodes,
            show,
            close,
            showSignPanel,
            loadFormInfo,
            selectUser,
            orgPicker,
            selected,
            initSign,
            getTask,
            getEnableRecallNodes,
            submitAction,
            signOk
        }
    }
}
</script>

<style lang="scss" scoped>
.action-content {
  margin-top: 20px;
  img {
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 20px;
    &:hover {
      border: 1px dashed var(--el-color-primary);
    }
  }

  :deep(.image-upload) {
    margin-bottom: 20px;
    .el-upload-list__item,
    .el-upload--picture-card {
      height: 65px;
      width: 65px;
    }
    .el-upload--picture-card {
      line-height: 70px;
    }
  }
}
canvas {
  border: 1px dashed #666666;
}
</style>